package com.example.demo.util;

import com.example.demo.config.EmailConfig;
import com.example.demo.entity.MailContent;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 自定义邮箱发送邮件
 *
 * @author zhanglei
 * @version 1.0
 * @date 2024-03-05 15:08
 */
@Component
public class MailSendSmtp {

    /**
     * 默认端口号
     */
    public static final Integer MAIL_DEFAULT_PORT = 25;

    @Autowired
    private EmailConfig emailConfig;



    /*{
        "attachmentNameList": [
        "附件名.pdf"
        ],
        "attachmentUrlList": [
        "https://invtest.nntest.cn/fp/BoRzE95ScXVqSZDehEhBZbz0YyYUFDwZ4Rr8oEuLzBfeM7rFoDSjYRKObeRPOHXyAnrfgbHtf4mz5r3-qvJRvQ.pdf"
        ],
        "ccEmail": "",
         "subject": "测试邮件",
         "text": "你好，这个测试邮件，请忽略",
         "toEmail": "1953623531.qq.com"
    }*/

    /**
     * 发送邮件，自己发送，不使用消息中心
     *
     * @param mailContent 邮件内容
     * @throws Exception 异常
     */
    public boolean send(MailContent mailContent) {

        try {
            //会发送到logstash。
            LogUtils.outLogInfo("mail", "sendMail", String.format("发送邮件，toEmail=%s，text=%s", mailContent.getToEmail(), mailContent.getText()));
            //抄送地址
            List<String> addresses = new ArrayList<>();
            addresses.add(mailContent.getToEmail());
            if (StringUtils.isNotBlank(mailContent.getCcEmail())) {
                String[] ccs = mailContent.getCcEmail().split(";");
                for (String addr : ccs) {
                    if (StringUtils.isNotBlank(addr)) {
                        addresses.add(addr);
                    }
                }
            }

            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
            // 设置邮件内容格式
            javaMailSender.setDefaultEncoding("utf-8");
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            javaMailSender.setHost(emailConfig.getServerUrl());
            // 设置默认端口,防止使用域名的时候，解析不正确
            Integer port = emailConfig.getServerPort() == null ? MAIL_DEFAULT_PORT : emailConfig.getServerPort();
            if (!MAIL_DEFAULT_PORT.equals(port)) {
                javaMailSender.setPort(port);
            }
            javaMailSender.setUsername(emailConfig.getUsername());
            javaMailSender.setPassword(emailConfig.getPassword());
            // 如果配置的发送邮箱为空，则使用邮件账号；否则使用发送邮箱
            helper.setFrom(StringUtils.isBlank(emailConfig.getSendMail()) ? emailConfig.getUsername() : emailConfig.getSendMail());
            //目标邮箱
            helper.setTo(mailContent.getToEmail());
            //邮件内容
            helper.setText(mailContent.getText(), true);
            //邮件标题
            helper.setSubject(mailContent.getSubject());
            // 增加抄送人
            if (StringUtils.isNotBlank(mailContent.getCcEmail())) {
                helper.setCc(addresses.toArray(new String[0]));
            }
            //附件，可以是多个，获取文件流
            if (CollectionUtils.isNotEmpty(mailContent.getAttachmentNameList())) {
                for (int i = 0; i < mailContent.getAttachmentNameList().size(); i++) {
                    String fileName = mailContent.getAttachmentNameList().get(i);
                    String url = mailContent.getAttachmentUrlList().get(i);
                    byte[] pdfBytes = HttpClientUtil.getRemoteResource(url, 5000);
                    if (pdfBytes != null) {
                        ByteArrayResource pdfResource = new ByteArrayResource(pdfBytes);
                        helper.addAttachment(MimeUtility.encodeText(fileName), pdfResource, "application/pdf");
                    }
                }
            }

            Properties props = new Properties();
            // 增加ssl配置
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.ssl.enable", "true");

            // 增加tsl配置
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.starttls.required", "true");

            if (!props.isEmpty()) {
                Session session = Session.getInstance(props, new javax.mail.Authenticator() {
                    @Override
                    protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(emailConfig.getUsername(), emailConfig.getPassword());
                    }
                });
                javaMailSender.setSession(session);
            }
            // 发送邮件
            javaMailSender.send(mimeMessage);
            return true;

        } catch (Exception e) {
            return false;
        }
    }
}

